/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */
package com.gadglet.data;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.gadglet.core.GadgletRequestWrapper;
import com.gadglet.data.utils.PMF;
import com.gadglet.params.ProfileFields;

/**
 * Utility class for Minglets Friends
 *
 */
public class FriendsUtils {

	static Logger log = Logger.getLogger("FriendsUtils");
	
	/**
	 * Create a new "friend" when a person accept an "invitation"
	 * @param request
	 * @return
	 */
	public static Friends createNewFriends(GadgletRequestWrapper request){
		
		String  initBy = null; 
		String  confirmedBy = null;
		boolean  existingFriends = false;
		Friends friends = null;
	
		
		if(!FriendsInvitationUtils.isMyInvitationValid(request))
			return null;
		if(request.getParameter(ProfileFields.PROFILE_FRIEND_ID.getParamName())==null)
			return null;
		
		initBy = request.getParameter(ProfileFields.PROFILE_FRIEND_ID.getParamName());
		confirmedBy = request.getCurrentUserProfileId();
		
		existingFriends = isMyFriend(request.getCurrentUserProfile() , request.getParameter(ProfileFields.PROFILE_FRIEND_ID.getParamName()));

		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.currentTransaction().begin();
		try {
			
			if(!existingFriends){
				friends = new Friends(initBy, confirmedBy);
				friends = pm.makePersistent(friends);
				pm.currentTransaction().commit();
		
		}
			
		} catch (Exception e) {
			log.warning(e.getMessage());
			
		} finally {
			if (pm.currentTransaction().isActive())
				pm.currentTransaction().rollback();
			pm.close();
		}
		
		FriendsInvitationUtils.deleteInvitation(request);
		
			
		return friends;
	}
	
	
	/**
	 * List of friends
	 * @param userProfile - current user profile
	 * @return List of friends
	 */
	public static List <Friends> getMyFriends(UserProfile userProfile) {

		List <Friends> friendsByMe = null;
		List <Friends> friendsToMe = null;
		List <Friends> allFriends = new ArrayList <Friends>();
				
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		Query query = pm.newQuery(Friends.class);
		
		try {

			query.setFilter("initBy == initByParam");
			query.declareParameters("String initByParam");
			
			friendsByMe = (List<Friends>) query.execute(userProfile.getProfileId());
			
			if(friendsByMe!=null)
				allFriends.addAll(friendsByMe);
					

		} catch (Exception e) {
			log.warning(e.getMessage());
		} finally {
	

			pm.close();
		}
		
			
		
		PersistenceManager pm2 = PMF.get().getPersistenceManager();
	
		Query query2 = pm2.newQuery(Friends.class);
		
		try {

			query2.setFilter("confirmedBy == confirmedByParam");
			query2.declareParameters("String confirmedByParam");
			
			friendsToMe = (List<Friends>) query2.execute(userProfile.getProfileId());
			
			if(friendsToMe!=null)
				allFriends.addAll(friendsToMe);

		} catch (Exception e) {
			log.warning(e.getMessage());
		} finally {
	

			pm2.close();
		}
		
		
	
		
		
		return allFriends;
	}
	
	
	
	/**
	 * Check if a user is a "friend" of the current user
	 * 
	 * @param userProfile - current user profile
	 * @param id - user it
	 * @return true if a user is "my" friend
	 */
	public static boolean isMyFriend(UserProfile userProfile , String id){
		List <Friends> friendsByMe = null;
		List <Friends> friendsToMe = null;
		
				
		PersistenceManager pm = null;	
		Query query = null;
		
		try {
			pm = PMF.get().getPersistenceManager();
			query = pm.newQuery(Friends.class);
			query.setFilter("initBy == initByParam && confirmedBy == confirmedByParam ");
			query.declareParameters("String initByParam, String confirmedByParam ");
			
			friendsByMe = (List<Friends>) query.execute(userProfile.getProfileId(), id);
		
			if(friendsByMe!=null && friendsByMe.size()>0)
				return true;
			
		} catch (Exception e) {
			log.warning(e.getMessage());
		} finally {
			
			pm.close();
		}
		
	
	
		
		PersistenceManager pm2 = PMF.get().getPersistenceManager();

		Query query2 = pm2.newQuery(Friends.class);
		
		try {

			query2.setFilter("initBy == initByParam && confirmedBy == confirmedByParam ");
			query2.declareParameters("String initByParam, String confirmedByParam ");
			
			friendsToMe = (List<Friends>) query2.execute(id, userProfile.getProfileId());
			
			if(friendsToMe!=null && friendsToMe.size()>0)
				return true;
					

		} catch (Exception e) {
			log.warning(e.getMessage());
		} finally {
			
			pm2.close();
		}
	
		return false;
	
	}
	
	
	
	
}
